import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../core/constants.dart';
import '../../shared/providers/quiz_provider.dart';

class QuizPage extends ConsumerStatefulWidget {
  final String category;

  const QuizPage({
    super.key,
    required this.category,
  });

  @override
  ConsumerState<QuizPage> createState() => _QuizPageState();
}

class _QuizPageState extends ConsumerState<QuizPage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadQuiz();
    });
  }

  void _loadQuiz() {
    final params = QuizParams(category: widget.category, count: 5);
    ref.read(quizQuestionsProvider(params).future).then((questions) {
      ref.read(quizStateProvider.notifier).initializeQuiz(questions);
    });
  }

  @override
  Widget build(BuildContext context) {
    final quizState = ref.watch(quizStateProvider);
    final questionsAsync = ref.watch(quizQuestionsProvider(
      QuizParams(category: widget.category, count: 5),
    ));

    return Scaffold(
      appBar: AppBar(
        title: Text('${widget.category} Quiz'),
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.deepPurple,
        foregroundColor: Colors.white,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Colors.deepPurple,
                Colors.indigo,
              ],
            ),
          ),
        ),
        leading: Container(
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12),
          ),
          child: IconButton(
            icon: const FaIcon(
              FontAwesomeIcons.arrowLeft,
              color: Colors.white,
              size: 18,
            ),
            onPressed: () => Navigator.pop(context),
          ),
        ),
        actions: [
          Container(
            margin: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: IconButton(
              icon: const FaIcon(
                FontAwesomeIcons.circleQuestion,
                color: Colors.white70,
                size: 18,
              ),
              onPressed: () {
                // Show quiz help
              },
            ),
          ),
        ],
      ),
      body: GestureDetector(
        onTap: () {
          // Dismiss keyboard when tapping outside
          FocusManager.instance.primaryFocus?.unfocus();
        },
        child: questionsAsync.when(
          data: (questions) {
            if (quizState.isCompleted) {
              return _buildResultsScreen(quizState);
            }
            return _buildQuizContent(quizState);
          },
          loading: () => const Center(child: CircularProgressIndicator()),
          error: (error, stack) => _buildErrorScreen(error.toString()),
        ),
      ),
    );
  }

  Widget _buildQuizContent(QuizState quizState) {
    final currentQuestion = quizState.currentQuestion;
    if (currentQuestion == null) {
      return const Center(child: Text('No questions available'));
    }

    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildProgressBar(quizState),
          const SizedBox(height: 24),
          _buildQuestionCard(currentQuestion),
          const SizedBox(height: 24),
          _buildAnswerOptions(currentQuestion, quizState),
          const Spacer(),
          _buildNavigationButtons(quizState),
        ],
      ),
    );
  }

  Widget _buildProgressBar(QuizState quizState) {
    final progress = (quizState.currentQuestionIndex + 1) / quizState.questions.length;
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              'Question ${quizState.currentQuestionIndex + 1} of ${quizState.questions.length}',
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: AppConstants.DARK_BLUE,
              ),
            ),
            Text(
              '${(progress * 100).round()}%',
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: AppConstants.PRIMARY_BLUE,
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        LinearProgressIndicator(
          value: progress,
          backgroundColor: Colors.grey[300],
          valueColor: const AlwaysStoppedAnimation<Color>(AppConstants.PRIMARY_BLUE),
        ),
      ],
    );
  }

  Widget _buildQuestionCard(dynamic currentQuestion) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Text(
        currentQuestion.question,
        style: const TextStyle(
          fontSize: 20,
          fontWeight: FontWeight.w600,
          color: AppConstants.DARK_BLUE,
          height: 1.4,
        ),
        textAlign: TextAlign.center,
      ),
    );
  }

  Widget _buildAnswerOptions(dynamic currentQuestion, QuizState quizState) {
    return Column(
      children: List.generate(currentQuestion.options.length, (index) {
        final isSelected = quizState.userAnswers[quizState.currentQuestionIndex] == index;
        return Container(
          margin: const EdgeInsets.only(bottom: 12),
          child: SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {
                ref.read(quizStateProvider.notifier).answerQuestion(index);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: isSelected ? AppConstants.PRIMARY_BLUE : Colors.white,
                foregroundColor: isSelected ? Colors.white : AppConstants.DARK_BLUE,
                padding: const EdgeInsets.all(16),
                side: BorderSide(
                  color: isSelected ? AppConstants.PRIMARY_BLUE : Colors.grey[300]!,
                  width: 2,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              child: Text(
                currentQuestion.options[index],
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
        );
      }),
    );
  }

  Widget _buildNavigationButtons(QuizState quizState) {
    return Row(
      children: [
        if (quizState.hasPrevious)
          Expanded(
            child: ElevatedButton(
              onPressed: () {
                ref.read(quizStateProvider.notifier).previousQuestion();
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.grey[300],
                foregroundColor: Colors.black87,
              ),
              child: const Text('Previous'),
            ),
          ),
        if (quizState.hasPrevious) const SizedBox(width: 16),
        Expanded(
          child: ElevatedButton(
            onPressed: quizState.userAnswers[quizState.currentQuestionIndex] != null
                ? () {
                    if (quizState.hasNext) {
                      ref.read(quizStateProvider.notifier).nextQuestion();
                    } else {
                      ref.read(quizStateProvider.notifier).completeQuiz();
                    }
                  }
                : null,
            child: Text(quizState.hasNext ? 'Next' : 'Complete'),
          ),
        ),
      ],
    );
  }

  Widget _buildResultsScreen(QuizState quizState) {
    final percentage = (quizState.score / quizState.questions.length * 100).round();
    
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 120,
            height: 120,
            decoration: BoxDecoration(
              color: AppConstants.PRIMARY_BLUE.withOpacity(0.1),
              shape: BoxShape.circle,
            ),
            child: Icon(
              percentage >= 80 ? Icons.emoji_events : 
              percentage >= 60 ? Icons.thumb_up : Icons.sentiment_satisfied,
              size: 60,
              color: AppConstants.PRIMARY_BLUE,
            ),
          ),
          const SizedBox(height: 24),
          const Text(
            'Quiz Complete!',
            style: TextStyle(
              fontSize: 28,
              fontWeight: FontWeight.bold,
              color: AppConstants.DARK_BLUE,
            ),
          ),
          const SizedBox(height: 16),
          Text(
            'Your Score',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '${quizState.score}/${quizState.questions.length} ($percentage%)',
            style: const TextStyle(
              fontSize: 36,
              fontWeight: FontWeight.bold,
              color: AppConstants.PRIMARY_BLUE,
            ),
          ),
          const SizedBox(height: 32),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {
                ref.read(quizStateProvider.notifier).resetQuiz();
                Navigator.pop(context);
              },
              child: const Text('Back to Learning'),
            ),
          ),
          const SizedBox(height: 16),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {
                ref.read(quizStateProvider.notifier).resetQuiz();
                _loadQuiz();
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.grey[300],
                foregroundColor: Colors.black87,
              ),
              child: const Text('Try Again'),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildErrorScreen(String error) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red,
          ),
          const SizedBox(height: 16),
          const Text(
            'Error loading quiz',
            style: TextStyle(
              fontSize: 18,
              color: Colors.red,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            error,
            style: const TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Go Back'),
          ),
        ],
      ),
    );
  }
} 